import { getAllGroupByUid } from '@/api/inform'
const api_url = 'ws://localhost:8080/'

const websocket = {
  baseURL: api_url + process.env.VUE_APP_BASE_API,
  runing: false,
  sockets: {},
  history: {},
  initSockets: function(uid, username) {
    getAllGroupByUid(uid).then(
      res => {
        if (res.data.status === 200) {
          for (const i in res.data.items) {
            this.sockets[res.data.items[i].name] = new WebSocket(this.baseURL + '/webSocket/' + res.data.items[i].name + username)
            this.setDefaultEventListener(this.sockets[res.data.items[i].name], res.data.items[i].name)
            this.history[res.data.items[i].name] = []
          }
          this.initSuccess()
          this.runing = true
          return this
        }
      },
      res => {
        this.initFail(res)
      }
    )
  },
  bindHistory: (history, name) => {
    this.history[name] = history
  },
  setDefaultEventListener: (socket, name) => {
    socket.onopen = () => {
      console.log('ws连接状态：' + socket.readyState)
      socket.send(JSON.stringify({ message: '连接成功' }))
    }
    socket.onmessage = (data) => {
      console.log('接收到来自服务器的消息：')
      console.log(data)
      const form = JSON.parse(data.data)
      console.log(form)
      if (form.message === 'new dialog') {
        const msg = Object.assign({}, JSON.parse(form.items))
        console.log(msg)
        this.history[name].push(msg)
        if (msg.sender.id === this.id) {
          const msgBox = document.getElementById('message-box')
          this.form.content = ''
          setTimeout(
            () => {
              msgBox.scrollTo({
                top: msgBox.scrollHeight,
                behavior: 'smooth'
              })
            }, 200
          )
        } else {
          this.$notify({
            title: msg.sender.name,
            message: (msg.content.length > 25 ? msg.content.substring(0, 25) + '...' : msg.content),
            type: 'success',
            duration: 4000
          })
        }
      }
    }
    socket.onclose = () => {
      console.log('ws连接状态：' + socket.readyState)
    }
    socket.onerror = function(error) {
      console.log(error)
    }
  },
  initSuccess: () => {},
  initFail: () => {},
  close: () => {
    for (const i in this.sockets) {
      this.sockets[i].close()
    }
  }

}

export default websocket
